#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>

// 每次重新分配多分配10个字节
#define ALLOC_STEP 10

int mygetline(int fd, char **line, int *n, int *eof);

int main(int argc, char **argv)
{
	char* line;
	int capacity = 0;
	int count;
	int fd;
	int eof = 0;

	fd = open(argv[1], O_RDONLY);

	while (!eof) {
		count = mygetline(fd, &line, &capacity, &eof);
		//printf("[Count: %d]\n", count);
	}

	return 0;
}

int mygetline(int fd, char **line, int *n, int *eof)
{
	int count = 0;
	int r;
	char buf[1];

	do {
		r = read(fd, buf, 1); // 一次只读一个字符
		count++;

		if (0 == r) {
			*eof = 1;
		}

		if (count >= (*n)) { // 等于的时候还需要一个位置放'\0'，也需要扩容
			if (*n == 0 || *line == NULL) {
				//printf("初次分配（%d）\n", ALLOC_STEP);
				*line = malloc(ALLOC_STEP);
				*n = ALLOC_STEP;
			} else {
				//printf("再分配（%d + %d）\n", *n, ALLOC_STEP);
				*line = realloc(*line, (*n) + ALLOC_STEP);
				*n += ALLOC_STEP;
			}
		}

		(*line)[count - 1] = buf[0]; // 要求保留输入中的'\n'
	} while (buf[0] != '\n');

	(*line)[count] = '\0';

	printf("%s", *line);

	return count;
}

